package com.hyq.learn.api.config.datasource.aop;

import com.hyq.learn.api.config.datasource.DatasourceContextHolder;
import com.hyq.learn.api.enumtype.DatasourceType;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.core.annotation.AnnotatedElementUtils;
import org.springframework.stereotype.Component;
import org.springframework.util.ClassUtils;

import java.util.Objects;


/**
 * @author heyuqin
 * @date 2024/5/30 14:48
 */
@Aspect
@Component
public class DatasourceAspect {

    @Around("@within(MyDs)")
    public Object dsJoinPoint(ProceedingJoinPoint joinPoint) {
        Class<?> targetClass = joinPoint.getTarget().getClass();
        Class<?> userClass = ClassUtils.getUserClass(targetClass);
        // 以下这种方式也是可以的
        // Class<?> anInterface = userClass.getInterfaces()[0];
        // MyDs annotation = anInterface.getAnnotation(MyDs.class);
        // 获取对应类中所有合并起来的注解信息
        MyDs dsAnnotation = AnnotatedElementUtils.findMergedAnnotation(userClass, MyDs.class);
        String datasourceKey = Objects.isNull(dsAnnotation) ? null : dsAnnotation.value();
        DatasourceType datasourceType = DatasourceType.parseByValue(datasourceKey);
        Object result = null;
        try {
            DatasourceContextHolder.setDatasourceType(datasourceType);
            result = joinPoint.proceed();
            return result;
        } catch (Throwable e) {
            throw new RuntimeException(e);
        } finally {
            DatasourceContextHolder.remove();
        }
    }
}
